package posts

import (
	"context"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/types/forum"

	"github.com/zeromicro/go-zero/core/logx"
)

type DeletePostsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeletePostsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeletePostsLogic {
	return &DeletePostsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 删除我的香评 ##25.03.31## 历史遗留文件，暂不处理
func (l *DeletePostsLogic) DeletePosts(in *forum.DeletePostReq) (*forum.BaseResp, error) {
	if len(in.Ids) == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	if in.UpdatedBy == nil || *in.UpdatedBy == 0 {
		return nil, resultx.StatusError(resultx.FORUM_POST_AUTHOR_ID_INVALID, "")
	}

	var ids []any
	for _, id := range in.Ids {
		if id > 0 {
			ids = append(ids, id)
		}
	}
	if len(ids) == 0 {
		return &forum.BaseResp{}, nil
	}

	filterMap := make(map[string]map[string][]any)
	filterMap[model.ForumPostColumns.PostID] = map[string][]any{
		"in": ids,
	}
	filterMap[model.ForumPostColumns.PostAuthorID] = map[string][]any{
		"equalTo": {*in.UpdatedBy},
	}
	filterMap[model.ForumPostColumns.PostStatus] = map[string][]any{
		"notEqualTo": {globalkey.StatusDeleted},
	}
	list, _, err := l.svcCtx.Post.GetList(l.ctx, model.M{
		"select": ",",
	}, -1, filterMap)
	if err != nil {
		return nil, err
	}

	if len(list) == 0 {
		return &forum.BaseResp{}, nil
	}

	tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
	if err != nil {
		return nil, resultx.StatusError(resultx.DB_ERROR, "")
	}

	for _, v := range list {
		err = l.svcCtx.Post.SoftDelete(l.ctx, tx, v.PostID)
		if err != nil {
			tx.Rollback()
			return nil, err
		}
	}

	tx.Commit()

	return &forum.BaseResp{}, nil
}
